package com.example.myapplication1;

import android.app.Dialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.utils.PreferenceManager;

import java.util.Map;

public class GymActivity extends AppCompatActivity {
    private static final String TAG = "GymActivity";
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;
    private TextView catFoodStockText;
    private TextView freezeDriedStockText;
    private TextView catTreatsStockText;
    private Map<String, Integer> userFeedStock;
    private long userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);




            Log.d(TAG, "正在创建运动馆页面");
            setContentView(R.layout.activity_gym);

            // 初始化数据库和PreferenceManager




            databaseHelper = new DatabaseHelper(this);
            preferenceManager = new PreferenceManager(this);
            userId = preferenceManager.getUserId();

            if (userId <= 0) {
                Log.e(TAG, "Invalid user ID: " + userId);
                Toast.makeText(this, "用户未登录或ID无效", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }

            // 验证数据库表结构
            validateDatabaseTables();

            // 设置返回按钮
            ImageButton backButton = findViewById(R.id.back_button);
            backButton.setOnClickListener(v -> {
                Log.d(TAG, "返回按钮被点击，准备返回首页");
                finish(); // 结束当前Activity，返回到上一个Activity（首页）
            });

            // 初始化视图
            initViews();
            // 加载用户饲料库存
            loadUserFeedStock();
            // 加载猫咪图片
            loadCatImages();

        } catch (Exception e) {
            Log.e(TAG, "创建运动馆页面时出错: " + e.getMessage());
            Toast.makeText(this, "页面加载失败", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        catFoodStockText = findViewById(R.id.cat_food_stock);
        freezeDriedStockText = findViewById(R.id.freeze_dried_stock);
        catTreatsStockText = findViewById(R.id.cat_treats_stock);

        // 设置喂养按钮点击事件
        Button feedXiaohuiButton = findViewById(R.id.feed_xiaohui_button);
        Button feedLazhuButton = findViewById(R.id.feed_lazhu_button);
        Button feedYuanbaoButton = findViewById(R.id.feed_yuanbao_button);

        feedXiaohuiButton.setOnClickListener(v -> showFeedDialog(21, "小灰"));
        feedLazhuButton.setOnClickListener(v -> showFeedDialog(22, "蜡烛"));
        feedYuanbaoButton.setOnClickListener(v -> showFeedDialog(23, "元宝"));
    }

    private void loadUserFeedStock() {
        userFeedStock = databaseHelper.getUserFeedStock(userId);
        Log.d(TAG, "loadUserFeedStock - Current feed stock: " + userFeedStock.toString());
        
        // 更新库存显示
        catFoodStockText.setText(userFeedStock.getOrDefault("营养猫粮", 0) + "份");
        freezeDriedStockText.setText(userFeedStock.getOrDefault("小猫冻干", 0) + "份");
        catTreatsStockText.setText(userFeedStock.getOrDefault("营养猫条", 0) + "份");
    }

    private void loadCatImages() {
        // 加载猫咪图片
        ImageView xiaohuiImage = findViewById(R.id.cat_xiaohui_image);
        ImageView lazhuImage = findViewById(R.id.cat_lazhu_image);
        ImageView yuanbaoImage = findViewById(R.id.cat_yuanbao_image);

        // 设置图片资源
        xiaohuiImage.setImageResource(R.drawable.cat_xiaohui);
        lazhuImage.setImageResource(R.drawable.cat_lazhu);
        yuanbaoImage.setImageResource(R.drawable.cat_yuanbao);
    }

    private void showFeedDialog(int catId, String catName) {
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_feed);
        dialog.setCancelable(true);

        TextView titleText = dialog.findViewById(R.id.dialog_title);
        titleText.setText("喂养 " + catName);

        // 获取输入框和库存显示
        TextView catFoodStockText = dialog.findViewById(R.id.cat_food_stock_text);
        TextView freezeDriedStockText = dialog.findViewById(R.id.freeze_dried_stock_text);
        TextView catTreatsStockText = dialog.findViewById(R.id.cat_treats_stock_text);

        // 显示当前库存
        catFoodStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("营养猫粮", 0)));
        freezeDriedStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("小猫冻干", 0)));
        catTreatsStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("营养猫条", 0)));

        EditText catFoodAmount = dialog.findViewById(R.id.cat_food_amount);
        EditText freezeDriedAmount = dialog.findViewById(R.id.freeze_dried_amount);
        EditText catTreatsAmount = dialog.findViewById(R.id.cat_treats_amount);

        Button cancelButton = dialog.findViewById(R.id.btn_cancel);
        Button confirmButton = dialog.findViewById(R.id.btn_confirm);

        cancelButton.setOnClickListener(v -> dialog.dismiss());
        confirmButton.setOnClickListener(v -> {
            try {
                // 获取输入的数量
                String catFoodStr = catFoodAmount.getText().toString();
                String freezeDriedStr = freezeDriedAmount.getText().toString();
                String catTreatsStr = catTreatsAmount.getText().toString();

                Log.d(TAG, "Feeding attempt - Cat: " + catName + " (ID: " + catId + ")");
                Log.d(TAG, "Input amounts - Cat Food: " + catFoodStr + 
                         ", Freeze Dried: " + freezeDriedStr + 
                         ", Cat Treats: " + catTreatsStr);

                // 检查是否至少输入了一个数量
                if (TextUtils.isEmpty(catFoodStr) && 
                    TextUtils.isEmpty(freezeDriedStr) && 
                    TextUtils.isEmpty(catTreatsStr)) {
                    Toast.makeText(this, "请至少输入一种饲料的数量", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 验证输入数量是否合法
                boolean isValid = true;
                String errorMessage = "";

                // 检查营养猫粮
                if (!TextUtils.isEmpty(catFoodStr)) {
                    int amount = Integer.parseInt(catFoodStr);
                    int stock = userFeedStock.getOrDefault("营养猫粮", 0);
                    if (amount <= 0) {
                        isValid = false;
                        errorMessage = "营养猫粮数量必须大于0";
                    } else if (amount > stock) {
                        isValid = false;
                        errorMessage = "营养猫粮库存不足";
                    }
                }

                // 检查小猫冻干
                if (isValid && !TextUtils.isEmpty(freezeDriedStr)) {
                    int amount = Integer.parseInt(freezeDriedStr);
                    int stock = userFeedStock.getOrDefault("小猫冻干", 0);
                    if (amount <= 0) {
                        isValid = false;
                        errorMessage = "小猫冻干数量必须大于0";
                    } else if (amount > stock) {
                        isValid = false;
                        errorMessage = "小猫冻干库存不足";
                    }
                }

                // 检查营养猫条
                if (isValid && !TextUtils.isEmpty(catTreatsStr)) {
                    int amount = Integer.parseInt(catTreatsStr);
                    int stock = userFeedStock.getOrDefault("营养猫条", 0);
                    if (amount <= 0) {
                        isValid = false;
                        errorMessage = "营养猫条数量必须大于0";
                    } else if (amount > stock) {
                        isValid = false;
                        errorMessage = "营养猫条库存不足";
                    }
                }

                if (!isValid) {
                    Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
                    return;
                }

                // 处理喂养
                boolean success = true;

                // 处理营养猫粮
                if (!TextUtils.isEmpty(catFoodStr)) {
                    int amount = Integer.parseInt(catFoodStr);
                    if (amount > 0) {
                        success &= databaseHelper.recordFeeding(userId, catId, "营养猫粮", amount);
                    }
                }

                // 处理小猫冻干
                if (!TextUtils.isEmpty(freezeDriedStr)) {
                    int amount = Integer.parseInt(freezeDriedStr);
                    if (amount > 0) {
                        success &= databaseHelper.recordFeeding(userId, catId, "小猫冻干", amount);
                    }
                }

                // 处理营养猫条
                if (!TextUtils.isEmpty(catTreatsStr)) {
                    int amount = Integer.parseInt(catTreatsStr);
                    if (amount > 0) {
                        success &= databaseHelper.recordFeeding(userId, catId, "营养猫条", amount);
                    }
                }

                if (success) {
                    Toast.makeText(this, "喂养成功！", Toast.LENGTH_SHORT).show();
                    // 重新加载库存
                    loadUserFeedStock();
                    dialog.dismiss();
                } else {
                    Toast.makeText(this, "喂养失败，请稍后再试", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请输入有效的数量", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Log.e(TAG, "喂养时出错: " + e.getMessage());
                Toast.makeText(this, "操作失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show();
    }

    // 验证数据库表结构
    private void validateDatabaseTables() {
        SQLiteDatabase db = databaseHelper.getReadableDatabase();
        
        try {
            // 检查各个表是否存在
            String[] tablesToCheck = {"feeding_records", "users", "orders", "order_items", "user_products"};
            
            for (String table : tablesToCheck) {
                Cursor cursor = db.rawQuery(
                    "SELECT name FROM sqlite_master WHERE type='table' AND name=?", 
                    new String[]{table});
                boolean exists = cursor != null && cursor.getCount() > 0;
                if (cursor != null) {
                    cursor.close();
                }
                
                Log.d(TAG, "Table " + table + " exists: " + exists);
            }
            
            // 检查feeding_records表中是否有对应的记录
            Cursor recordCursor = db.rawQuery(
                "SELECT COUNT(*) FROM feeding_records WHERE user_id = ?", 
                new String[]{String.valueOf(userId)});
            
            int recordCount = 0;
            if (recordCursor != null && recordCursor.moveToFirst()) {
                recordCount = recordCursor.getInt(0);
                recordCursor.close();
            }
            
            Log.d(TAG, "Number of feeding records for user " + userId + ": " + recordCount);
            
        } catch (Exception e) {
            Log.e(TAG, "Error validating database tables: " + e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 